<template>
  <el-dialog :model-value="visible" :title="title" width="500" :close-on-click-modal="false" :show-close="false">
    <el-form ref="formRef" :model="form" :rules="formRules" label-width="auto">
      <el-form-item label="产品名称">
        <el-input readonly :model-value="props.productName"></el-input>
      </el-form-item>
      <el-form-item label="配件名称" prop="partName">
        <el-input v-model="form.partName"></el-input>
      </el-form-item>
      <el-form-item label="配件价格" prop="price">
        <el-input-number :min="0" :step="0.1" :precision="2" v-model.number="form.price"></el-input-number>
      </el-form-item>
    </el-form>
    <template #footer>
      <div class="dialog-footer">
        <el-button type="primary" @click="submit">提交</el-button>
        <el-button @click="emits('close', false)">关闭</el-button>
      </div>
    </template>
  </el-dialog>
</template>
<script lang="ts" setup>
import ApiTree from '@/server/api-tree';
import type { ProductPartVO } from '@/server/productPart/types';
import { type FormRules, type FormInstance, ElMessage } from 'element-plus';
import { reactive, ref, watch } from 'vue';

const emits = defineEmits(["close"])
const props = withDefaults(defineProps<
  {
    productCode: string; productName: string; data: ProductPartVO | null, visible: boolean
  }>(), {
  productCode: "",
  productName: "",
  data: null,
  visible: false
});
/** 表单定义 */
const title = ref<string>("");
const form = ref<ProductPartVO>({
  guid: "",
  productCode: "",
  productName: "",
  partName: "",
  price: 0,
  ctime: "",
  cuser: ""
});
const formRef = ref<FormInstance>();
const formRules = reactive<FormRules<ProductPartVO>>({
  partName: [{ required: true, message: "配件名称不能为空" }],
  price: [{ required: true, message: "价格不能为空" }, { type: "number", min: 0, message: "价格不能小于0" }],
})
const initForm = () => {
  form.value = {
    guid: "",
    productCode: props.productCode,
    productName: props.productName,
    partName: "",
    price: 0,
    ctime: "",
    cuser: ""
  }
}
/**
 * 监听属性变化
 */
watch(() => props.visible, () => {
  if (props.data) {
    title.value = "编辑配件信息"
    form.value = props.data;
  } else {
    title.value = "添加配件信息"
    initForm();
  }
}, { immediate: true })
/**提交表单 */
const submit = () => {
  formRef.value?.validate(async (valid) => {
    if (valid) {
      //
      if (props.data) {
        const { success, msg } = await ApiTree.productPart.update(form.value);
        if (success) {
          ElMessage.success(msg);
        }
        emits("close", success);
      } else {
        const { success, msg } = await ApiTree.productPart.create(form.value);
        if (success) {
          ElMessage.success(msg);
        }
        emits("close", success);
      }
    }
  })
}
</script>
<style lang="scss" scope></style>
